package com.seed.core.pojo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.seed.core.exception.ServiceException;
import com.seed.core.pojo.dto.SeedMessageDTO;
import com.seed.core.pojo.entity.SeedBaseEntity;
import com.seed.core.pojo.manager.SeedSystemManager;
import com.seed.core.pojo.service.SeedSystemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author gchiaway
 * 日期: 2020-07-20
 * 时间: 15:22
 */
@Slf4j
public class SeedSystemController<Service extends SeedSystemService<Entity>, Manager extends SeedSystemManager<Entity>, Entity extends SeedBaseEntity> extends SeedBaseController {

    @Autowired
    protected Manager baseManager;

    @Autowired
    protected Service baseService;

    protected Class<Service> serviceClass = currentServiceClass();
    protected Class<Manager> managerClass = currentManagerClass();
    protected Class<Entity> realEntityClass = currentModelClass();

    protected Class<Service> currentServiceClass() {
        return (Class<Service>) ReflectionKit.getSuperClassGenericType(getClass(), SeedSystemController.class, 0);
    }

    protected Class<Manager> currentManagerClass() {
        return (Class<Manager>) ReflectionKit.getSuperClassGenericType(getClass(), SeedSystemController.class, 1);
    }

    protected Class<Entity> currentModelClass() {
        return (Class<Entity>) ReflectionKit.getSuperClassGenericType(getClass(), SeedSystemController.class, 2);
    }

    /**
     * 初始化导入环境
     *
     * @param request 请求,包含了excel file
     * @param clazz   返回的指定类型
     * @return 读取request解析出对象列表
     */
    protected <T> List<T> initImportExcelData(HttpServletRequest request, Class<?> clazz) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = fileMap.get("file");
        ImportParams params = new ImportParams();
        params.setTitleRows(2);
        params.setHeadRows(1);
        try {
            return ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 导入
     *
     * @param request
     * @return
     */
    protected Result<?> importExcel(HttpServletRequest request) {
        Result<?> result = new Result<>();
        List<Entity> list = this.initImportExcelData(request, this.realEntityClass);
        if (ObjectUtils.isEmpty(list) || list.isEmpty()) {
            return result.error500("excel数据为空");
        }
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0;
        for (int i = 0; i < list.size(); i++) {
            int lineNumber = i + 1;
            Entity data = list.get(i);
            SeedMessageDTO checkResult;
            try {
                checkResult = baseService.excelDataFilter(data);
            } catch (ServiceException e) {
                errorMessage.add("第 " + lineNumber + " 行：数据校验失败");
                continue;
            }
            if (checkResult.getSuccess()) {
                SeedMessageDTO baseSeedDTO;
                try {
                    baseSeedDTO = baseService.save(data);
                } catch (ServiceException e) {
                    //保存失败
                    errorMessage.add("第 " + lineNumber + " 行：保存失败");
                    continue;
                }
                if (baseSeedDTO.getSuccess()) {
                    successLines = successLines + 1;
                } else {
                    //保存失败
                    errorMessage.add("第 " + lineNumber + " 行：" + baseSeedDTO.getMessage());
                }
            } else {
                //check失败
                errorMessage.add("第 " + lineNumber + " 行：" + checkResult.getMessage());
            }
        }
        return this.importExcelResult(successLines, errorMessage);
    }


    /**
     * 导出excel
     *
     * @param request
     */
    protected ModelAndView exportXls(HttpServletRequest request, Entity object, String title) {
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.1 组装查询条件
        QueryWrapper<Entity> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        // Step.2 获取导出数据
        List<Entity> pageList;
        try {
            pageList = baseService.list(queryWrapper);
        } catch (ServiceException e) {
            mv.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            return mv;
        }
        // Step.3 AutoPoi 导出Excel
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, this.realEntityClass);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }
}
